package net.laenzlinger.decision.web;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.http.HttpServletResponse;

import net.laenzlinger.decision.domain.RuleBase;

import org.apache.commons.io.IOUtils;
import org.springframework.roo.addon.web.mvc.controller.RooWebScaffold;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.support.ByteArrayMultipartFileEditor;

@RooWebScaffold(path = "rulebases", formBackingObject = RuleBase.class)
@RequestMapping("/rulebases")
@Controller
public class RuleBaseController {

	@InitBinder
	protected void initBinder(ServletRequestDataBinder binder) {
		binder.registerCustomEditor(byte[].class,
				new ByteArrayMultipartFileEditor());
	}

	@RequestMapping(value = "/download/{id}", method = RequestMethod.GET)
	public String showrulebase(  @PathVariable("id") Long id,
			HttpServletResponse response,
			Model model) {
		RuleBase rules = RuleBase.findRuleBase(id);

		try {
			response.setHeader("Content-Disposition", "inline;filename=\"filename\"");
			OutputStream out = response.getOutputStream();
			response.setContentType("");
			IOUtils.copy( new ByteArrayInputStream(rules.getContent()),out);
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}
